package com.springapp.mvc.newspsi.service;

import com.springapp.mvc.newspsi.model.Comment;
import com.springapp.mvc.newspsi.model.News;
import com.springapp.mvc.newspsi.repositories.NewsRepositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * User: Станислав
 * Date: 15.09.14
 */
@Service

public class NewsService {
@Autowired
    private NewsRepositories newsRepositories;


    public NewsService() {
    }

    public void saveNews(News news) {
        newsRepositories.save(news);
    }

    public Iterable<News> getAllNews() {
        return newsRepositories.findAll();
    }
    public String allNewsText(){
        Iterable<News> news = getAllNews();
        String s ="";
        Iterator<News> newsIterator = news.iterator();
        while (newsIterator.hasNext()){
            s+=newsIterator.next().toString();
        }
        return s;
    }

    public void deleteNews(News news) {
        newsRepositories.delete(news);
    }

    public News findById(Integer id) {
        News newstmp=null;
        for (News news : getAllNews()) {
            newstmp=news;
            if (newstmp.getId_news() == id)
                return newstmp;

        }

        return newstmp;
    }

    public List<News> findByTitle(CharSequence title) {
        List<News> newsList = new ArrayList<News>();
        Iterator<News> newsIterator = getAllNews().iterator();
        News news = null;
        while (newsIterator.hasNext()) {
            news = newsIterator.next();
            if (news.getTitle().contains(title))
                newsList.add(news);
        }
        return newsList;
    }

    public List<News> findByText(CharSequence text) {
        List<News> newsList = new ArrayList<News>();
        Iterator<News> newsIterator = getAllNews().iterator();
        News news = null;
        while (newsIterator.hasNext()) {
            news = newsIterator.next();
            if (news.getText_news().contains(text))
                newsList.add(news);
        }
        return newsList;

    }
    public void addComment(News news,Comment comment){
        News tmp = news;
        Set<Comment> comments = news.getComments();
        comments.add(comment);
        tmp.setComments(comments);
        deleteNews(news);
        saveNews(tmp);
    }
}
